/************************************************************************
Purpose: Preparing bids data set (simulated bids counterpart)
*************************************************************************/

clear all
clear matrix
set more off
set linesize 255
pause on

** Get plant-period level variables from structural_model_input.dta
use "$MODEL_DATA_OUT/structural_model_input.dta", clear
keep if D_trade == 1


* Rename variables
rename heatoutput Hi
rename emission_val_prorated Eit
rename pm_mass_potential_max_16 Ebari
rename permit_alloc_prorated Ait

* Generate the share of allocated quantity of a plant in a period
rename period_num id_period
bysort id_period: egen total_allocation = sum(Ait)
gen Ai_share = Ait / total_allocation
label var Ai_share "allocated quantity / total allocation"

keep id_plant id_gpcb id_period Hi Ait Ai_share Eit Ebari apcd_max  
order id_plant id_gpcb id_period Hi Ait Ai_share Eit Ebari apcd_max
duplicates drop
sort id_plant id_period
tempfile plant_period_variables
save `plant_period_variables'


** Get plant-period-bid level variables from panel_plant-period-date-bid.dta
use "$TRADING_DATA_CLEAN/panel_plant-period-date-bid.dta", clear

* Rename variables
rename gpcb_id id_gpcb
rename commodity id_commodity
rename period id_period
rename bid_price bid_p
rename bid_qty bid_q
rename permit_holding_hyp bid_qE
rename week_num bid_week
rename max_week_num num_weeks_period
rename is_auction D_auction
rename consumed_period period_emissions

* Generate a new Bid ID
bysort id_gpcb id_period (bid_id): gen id_bid = _n
replace id_bid = . if missing(bid_q) & missing(trade_qty)
label var id_bid "Bid ID"
drop bid_id

* Add an indicator of whether a bid is placed in the first half of a period.
gen D_first_half = 0
replace D_first_half = 1 if bid_day_norm <= 0.5
replace D_first_half = . if bid_day_norm == .
label var D_first_half "=1 if a bid is placed in the first half of a period"

* Count the number of bids a plant placed in a period
bysort id_gpcb id_period: gen bid_count = _N
label var bid_count "Number of bids placed in the period"

keep id_gpcb id_period id_bid bid_count bid_qE bid_q bid_p bid_day_norm bid_week num_weeks_period D_first_half D_auction period_emissions D_cyc-D_esp

** Merge data sets
merge m:1 id_gpcb id_period using `plant_period_variables'
order id_plant id_gpcb id_period id_bid bid_count bid_qE bid_q bid_p bid_day_norm bid_week num_weeks_period D_first_half period_emissions
drop if _merge == 1
drop _merge
sort id_gpcb id_period id_bid
replace bid_count = 0 if missing(id_bid)

save "$MODEL_DATA_OUT/bids.dta", replace
export delimited using "$MODEL_DATA_OUT/bids.txt", nolabel delimiter(tab) replace
